//
//  YZXPaintView.m
//  Custom drawing board
//
//  Created by 叶周翔 on 2016/11/10.
//  Copyright © 2016年 yezx. All rights reserved.
//

#import "YZXPaintView.h"
#import "YZXPath.h"
@interface YZXPaintView ()
// 路径
@property (nonatomic, strong) YZXPath *path;
@property (nonatomic, strong) NSMutableArray *allPaths;

@end

@implementation YZXPaintView
/// 当每次手指开始触摸的时候开始划线
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    YZXPath *path = [YZXPath bezierPath];
    self.path = path;
    [self.allPaths addObject:path];
    path.lineWidth = self.lineWidth;
    path.lineCapStyle = kCGLineCapRound;
    path.lineJoinStyle = kCGLineCapRound;
    // 将当前的颜色储存在路径对象中
    path.pathColor = self.lineColor;
    // 起点
    UITouch *touch = [touches anyObject];
    CGPoint currentPoint = [touch locationInView:self];
    [path moveToPoint:currentPoint];
}

/// 手指离开时候的终点
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    UITouch *touch = [touches anyObject];
    // 离开时候的点
    CGPoint leavePoint = [touch locationInView:self];
    // 终点绘制
    [[self.allPaths lastObject] addLineToPoint:leavePoint];
    // 通知重绘
    [self setNeedsDisplay];
}

/// 绘制方法
- (void)drawRect:(CGRect)rect{
    for (YZXPath *path in self.allPaths) {
        [path.pathColor setStroke];
        [path stroke];
    }
}

- (void)eraser{
    self.lineColor = self.backgroundColor;
}

- (void)goBack{
    [self.allPaths removeLastObject];
    [self setNeedsDisplay];
}

- (void)clearScreen{
    [self.allPaths removeAllObjects];
    [self setNeedsDisplay];
}

#pragma mark - GETTER
- (NSMutableArray *)allPaths{
    if (_allPaths == nil) {
        _allPaths = [NSMutableArray array];
    }
    return _allPaths;
}
@end
